package com.amadeus.spin.devtool.soap.shooter.process;

import java.util.List;
import java.util.Stack;

import org.apache.log4j.Logger;
import org.w3c.dom.Node;

import com.amadeus.spin.devtool.soap.shooter.FatalException;
import com.amadeus.spin.devtool.soap.shooter.ProcessInput;
import com.amadeus.spin.devtool.soap.shooter.Shooter;
import com.amadeus.spin.standard.util.XPathHelper;

public class ForwardOutput implements ProcessInput {

  private static Logger log = Logger.getLogger(ForwardOutput.class);

  /**
   * Takes the list of entries to forward from the config parameter.
   * Searches for the entries in the previous output
   * Then Replaces the found entries in the input
   */
  @Override
  public String processInput(Stack<String> previousOutputs, String input, Node config) throws FatalException {
    String previousOutput = "";
    if (previousOutputs != null && previousOutputs.size() > 0) {
      previousOutput = previousOutputs.lastElement();
    }
    List<String> keys = XPathHelper.getProperties(config, "entry/@key");

    if ((previousOutput != null) && (input != null)) {
      for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        String open = "<" + key + ">";
        String close = "</" + key + ">";
        String shortTag = "<" + key + "/>";
        int startValue = previousOutput.indexOf(open);
        int endValue = previousOutput.indexOf(close, startValue);
        if (startValue != -1) {

          boolean found = false;
          String value = previousOutput.substring(startValue + 2 + key.length(), endValue);
          value = Shooter.replaceVariables(value);

          if (input.indexOf(open) != -1) {
            found = true;
            input = input.replaceAll(open + "(?s).*" + close, open + value + close);
          }
          if (input.indexOf(shortTag) != -1) {
            found = true;
            input = input.replaceAll(shortTag, open + value + close);
          }

          if (found) {
            log.info("forwarding " + key + " (= " + value + ") from previous output!");
          }
          else {
            log.info("can't forward " + key + " (tag not found in next input)");
          }
        }
        else {
          log.info("can't forward " + key + " (tag not found in previous output)");
        }
        if (keys.size() == 0) {
          log.warn("no <entry key=\"[TAG_NAME]\"/> defined");
        }
      }
    }

    return input;
  }
}